<template>
	<div>
		<!-- 面包屑导航区 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
		  <el-breadcrumb-item>参数列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图区域 -->
		<el-card>
			<!-- 警告提示框 -->
			 <el-alert
			    title="注意:只允许为第三级分类设置相关参数!"
			    type="warning" 
				:closable="false" 
				show-icon
				>
			  </el-alert>
			  <!-- 选择商品分类区域 -->
			  <el-row class="cat_opt">
				  <el-col>
					  <span>选择商品分类:</span>
					  <!-- 选择商品分类的级联选择框 -->
					  <el-cascader
					      v-model="selectedKeys"
					      :options="cateList"
					      :props="cascaderProps"
					      @change="handleChange"
						  clearable
						 ></el-cascader>
				  </el-col>
			  </el-row>
			  <!-- tabs导航栏 -->
			  <el-tabs v-model="activeName" @tab-click="handleTabClick">
				  <!-- 添加动态参数的面板 -->
			      <el-tab-pane label="动态参数" name="many">
					  <el-button type="primary" size="mini" :disabled="isBtnDisables" @click="addPara">添加参数</el-button>
				<!-- 动态表格区域 -->
					   <el-table
						  :data="manyTableData"
						  border
						  stripe
						  style="width: 100%">
					  <el-table-column type="expand">
						<template slot-scope="scope">
						  		<el-tag closable v-for="(item,i) in scope.row.attr_vals" :kye="i"
								@close="closeTag(i,scope.row)"
								> {{item}} </el-tag>
								<el-input
								  class="input-new-tag"
								  v-if="scope.row.inputVisible"
								  v-model="scope.row.inputValue"
								  ref="saveTagInput"
								  size="small"
								  @keyup.enter.native="handleInputConfirm(scope.row)"
								  @blur="handleInputConfirm(scope.row)"
								>
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
						 </template>
					  </el-table-column>
					  <el-table-column type="index"></el-table-column>
					  <el-table-column
					     prop="attr_name"
					     label="参数名称">                                                                   
				      </el-table-column>
				      <el-table-column
						label="操作">
						  <template slot-scope="scope">
							<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
							<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParaById(scope.row.attr_id)">删除</el-button>
						  </template>
					  </el-table-column>
					</el-table>
				 </el-tab-pane>
				 
				  <!-- 添加静态属性的面板 -->
				  <el-tab-pane label="静态属性" name="only">
					  <el-button type="primary" size="mini" :disabled="isBtnDisables" @click="addPara">添加属性</el-button>
				   <!-- 静态表格区域 -->
					   <el-table
						  :data="onlyTableData"
						  border
						  stripe
						  style="width: 100%">
						  <el-table-column type="expand">
							 <template slot-scope="scope">
							   		<el-tag closable v-for="(item,i) in scope.row.attr_vals" :kye="i"
							 		@close="closeTag(i,scope.row)"
							 		> {{item}} </el-tag>
							 		<el-input
							 		  class="input-new-tag"
							 		  v-if="scope.row.inputVisible"
							 		  v-model="scope.row.inputValue"
							 		  ref="saveTagInput"
							 		  size="small"
							 		  @keyup.enter.native="handleInputConfirm(scope.row)"
							 		  @blur="handleInputConfirm(scope.row)"
							 		>
							 		</el-input>
							 		<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
							   </template>
						  </el-table-column>
						  <el-table-column type="index"></el-table-column>
						  <el-table-column
							prop="attr_name"
							label="属性名称">
						  </el-table-column>
						  <el-table-column
							label="操作">
							<template slot-scope="scope">
								<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
								<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParaById(scope.row.attr_id)">删除</el-button>
							</template>
						  </el-table-column>
						</el-table>
				  </el-tab-pane>
			  </el-tabs>
			  
			  
			  
			  <!-- 添加参数对话框 -->
			  <el-dialog
			    :title="'添加'+titleText"
			    :visible.sync="addParadialogVisible"
			    width="50%"
			    @close="addParaDialogClosed"
			   >
			   <!-- 内容主体区域，这里有一个匿名插槽 -->
			    <el-form :model="addParaForm" :rules="addParaFormRules" ref="addCatFormRef" label-width="100px">
			  	<el-form-item :label="titleText" prop="attr_name">
			  	  <el-input v-model="addParaForm.attr_name"></el-input>
			  	</el-form-item>
				</el-form>
			    <!-- 底部区域，这里是一个具名插槽 -->
			    <span slot="footer" class="dialog-footer">
			      <el-button @click="addParadialogVisible= false">取 消</el-button>
			      <el-button type="primary" @click="addParaTo">确 定</el-button>
			    </span>
			  </el-dialog>
			  
			  <!-- 修改参数对话框 -->
			  <el-dialog
			    :title="'修改'+titleText"
			    :visible.sync="editParadialogVisible"
			    width="50%"
			    @close="editParaDialogClosed"
			   >
			   <!-- 内容主体区域，这里有一个匿名插槽 -->
			    <el-form :model="editParaForm" :rules="addParaFormRules" ref="editCatFormRef" label-width="100px">
			  	<el-form-item :label="titleText" prop="attr_name">
			  	  <el-input v-model="editParaForm.attr_name"></el-input>
			  	</el-form-item>
			  	</el-form>
			    <!-- 底部区域，这里是一个具名插槽 -->
			    <span slot="footer" class="dialog-footer">
			      <el-button @click="editParadialogVisible= false">取 消</el-button>
			      <el-button type="primary" @click="editParaTo">确 定</el-button>
			    </span>
			  </el-dialog>
		</el-card>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				//获取的所有列表信息
				cateList:[],
				//选中的级联选择框的id值
				selectedKeys:[],
				//指定级联选择器的配置对象
				cascaderProps:{
					expandTrigger: 'hover',
					//获取的数据中的id
					value: 'cat_id',
					//显示在页面上的每一项的内容
					label:'cat_name',
					//下一层级
					children:'children',
				},
				//tabs导航栏选中的便签页
				activeName:'many',
				manyTableData:[],
				onlyTableData:[],
				//开始添加参数的对话框相关
				addParadialogVisible:false,
				addParaForm:{},
				addParaFormRules:{
					attr_name:[{ required: true, message: '请输入内容', trigger: 'blur' }]
				},
				//开始修改对话框的参数设置
				editParadialogVisible:false,
				editParaForm:{
					attr_name:''
				},
				
			}
		},
		created(){
			this.getCateList()
		},
		methods:{
			//获取所有的分类的数据列表
			async getCateList(){
				const{data:res}=await this.$http.get('categories')
				if(res.meta.status!==200)return this.$message.error(res.meta.msg)
				this.$message.success(res.meta.msg)
				this.cateList=res.data
			},
			//选中级联选择框时发生
			handleChange(){
				this.getParamsData()
			},
			//tab便签点击事件
		  handleTabClick(tab, event) {
			  this.getParamsData()
		  },
		  //获取对应参数的列表数据(静态/动态)
		  async getParamsData(){
			  //它只能选中第三级
			  // this.addcatForm.cat_pid=this.selectedKeys[this.selectedKeys.length-1]
			  // this.addcatForm.cat_level=3
			  //根据所选分类的id,和当前所处的面板,获取对应的参数
			  if(this.selectedKeys.length!==3){
				  this.manyTableData=[]
				  this.onlyTableData=[]
			  }
			  const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{
			  	params:{sel:this.activeName}
			  })
			  if(res.meta.status!==200)return this.$message.error(res.meta.msg)
			  //但是现在获取到的数据有两种情况,可能是静态数据,也可能是动态数据
			  //需要做一下判断,分别保存到不同的地方,后续使用
			  res.data.forEach(item=>{
				  //把获得的数据分割掉,组成新的数组,把字符串变成数组
				  item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[],
				  //标签的文本框的显示和隐藏
				  item.inputVisible= false,
				   //标签的文本框的输入内容
				  item.inputValue= ''
			  })
			  if(this.activeName==='many'){
				  this.manyTableData=res.data
			  }else{
				  this.onlyTableData=res.data
			  }
		  },
		  addPara(){
			  this.addParadialogVisible=true
		  },
		  //发起请求,添加参数
		  addParaTo(){
			  //先对表单进行预验证
			  this.$refs.addCatFormRef.validate(async valid=>{
				  if(!valid)return 
				  //验证通过之后发起请求
				  const{data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{
					  attr_name:this.addParaForm.attr_name,
					  attr_sel:this.activeName
				  })
				  if(res.meta.status!==201)return this.$message.error(res.meta.msg)
				  this.$message.success(res.meta.msg)
				  this.addParadialogVisible=false
				  //刷新参数列表
				  this.getParamsData()
			  })
		  },
		  addParaDialogClosed(){
			this.addParaForm={}
		  },
		  editParaDialogClosed(){
			  this.$refs.editCatFormRef.resetFields()
		  },
		  //显示编辑对话框
		  async showEditDialog(val){
			  this.editParadialogVisible=true
			  //通过参数发起请求,获取到对应id的数据,然后存储起来使用
			  const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${val}`,{
				  params:{attr_sel:this.activeName}
			  })
			  //将获取到的数据存储起来
			  this.editParaForm=res.data
		  },
		  //发起请求,修改参数
		  async editParaTo(){
			const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editParaForm.attr_id}`,{
				attr_name:this.editParaForm.attr_name,
				attr_sel:this.activeName,
				attr_vals:this.editParaForm.attr_vals
			})
			if(res.meta.status!==200)return this.$message.error(res.meta.msg)
			this.$message.success(res.meta.msg)
			this.getParamsData()
			this.editParadialogVisible=false
		  },
		  //删除属性/参数
		  async removeParaById(id){
		  	//弹窗询问是否删除数据
		  	const confirmResult=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
		  	          confirmButtonText: '确定',
		  	          cancelButtonText: '取消',
		  	          type: 'warning'
		  	        }).catch(err=>err)
		  	//如果用户确认删除，则返回字符串confirm
		  	//如果用户确认取消，则返回字符串cancel
		  	if(confirmResult!=='confirm')return this.$message.info("已经取消了删除")
		  	const{data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
		  	if(res.meta.status!==200)return this.$message.error(res.meta.msg)
		  	this.$message.success(res.meta.msg)
		  	this.getParamsData()
		  },
		 //  //tag标签的事件显示input
		  showInput(val) {
		  	val.inputVisible = true;
			//$nextTick方法的作用.当页面上的元素被重新渲染之后,才执行这里面回调函数的代码
			//在这里,是变成input函数之后,再获取焦点
		  	this.$nextTick(_ => {
			//文本框自动获得焦点
		  	  this.$refs.saveTagInput.$refs.input.focus();
		  	});
		    },
		  //tag标签的事件,把添加的标签显示出来,并保存到数据库
		   async handleInputConfirm(val) {
				//如果输入的字符串全是字符,则清空输入框
				if(val.inputValue.trim().length ===0){
					val.inputValue=''
					val.inputVisible=false
					return
				}
				//如果没有return,则需要做后续处理
				let inputValue = val.inputValue;
				if (inputValue) {
				 //发起请求,添加新的标签
				  val.attr_vals.push(val.inputValue.trim())
				  val.inputValue=''
				  val.inputVisible=false
				  //发起请求,保存本次参数到数据库
				  const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${val.attr_id}`,{
				  	attr_name:val.attr_name,
				  	attr_sel:val.attr_sel,
					attr_vals:val.attr_vals.join(' ')
				  })
				 if(res.meta.status!==200)return this.$message.error(res.meta.msg)
				 this.$message.success(res.meta.msg)
				 //这里不需要重新刷新,一旦重新刷新,下拉菜单就会收起来
				}
			},
			//删除对应的tag标签
			async closeTag(i,val){
				//这个splice会修改原数组,所以修改完成之后,发起请求,就可以完成删除了.
				val.attr_vals.splice(i,1)
				//发起请求:将对attr_vals的操作保存到数据库中
				const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${val.attr_id}`,{
				 	attr_name:val.attr_name,
				 	attr_sel:val.attr_sel,
					attr_vals:val.attr_vals.join(' ')
				 })
				 if(res.meta.status!==200)return this.$message.error(res.meta.msg)
				 this.$message.success('删除标签成功')
			}
		},
		
		
		computed:{
			//因为要么不选中,要么选中三级,所以:
			isBtnDisables(){
				if(this.selectedKeys.length!==3)return true
				return false
			},
			//获取最末尾一级别的id
			cateId(){
				if(this.selectedKeys.length==3)return this.selectedKeys[2]
				return null
			},
			//计算弹出框的显示文本
			titleText(){
				//当点击的是动态参数时
				if(this.activeName==='many'){
				  return '动态参数'
			    }else{
				  return '静态参数'
			    }
			},
		}
	}
</script>

<style lang="stylus" scoped>
	.cat_opt{
		margin: 15px 0;
	}
	.el-tag{
		margin-right: 15px;
	}
	 .input-new-tag {
	    width: 90px;
	    margin-left: 10px;
	    vertical-align: bottom;
	  }
</style>
